$(function () {
  $("#loginBox #link-login").on("click", () => {
    //点击按钮loginBox 盒子隐藏,registerBox 显示
    $("#loginBox").hide();
    $("#registerBox").show();
  });
  $("#registerBox #link-login").on("click", () => {
    //点击按钮loginBox 盒子显示,registerBox 隐藏
    $("#registerBox").hide();
    $("#loginBox").show();
  });
  //需求2:自定义校验规则
  let form = layui.form;
  //form.verify()的值是一个对象
  form.verify({
    //属性是规则名称,值可以使数组或者函数
    pwd: [
      /^[\S]{6,15}$/,
      //报错信息
      "密码长度为6-15个字符,岂不能包含空格",
    ],
    repwd: function (value) {
      let pwd = $("#registerBox [name=password]").val();
      if (value !== pwd) {
        return "两次密码不一致";
      }
    },
  });

  //希求3:注册(axios)
  let layer = layui.layer;
  //注册事件
  $("#form-reg").on("submit", function (e) {
    e.preventDefault();

    //发送添加请求

    axios({
      method: "POST",
      url: "/api/reguser",
      data: $("#form-reg").serialize(),
    }).then((res) => {
      let obj = res.data;
      console.log(res.data);
      //判断状态
      if (obj.status !== 0) {
        return layer.msg(obj.message);
      }
      //注册成功
      layer.msg(obj.message);
      //清空表单
      $("#form-reg")[0].reset();
      //切换到登陆
      $("#registerBox #link-login").click();
    });
  });

  //需求4:登陆
  $("#form-login").on("submit", function (e) {
    e.preventDefault();
    //发送请求
    axios({
      method: "post",
      url: "/api/login",
      data: $("#form-login").serialize(),
    }).then((res) => {
      let obj = res.data;
      //console.log(obj);
      if (obj.status !== 0) {
        return layer.msg(obj.message);
      }
      //成功,提示,跳转,保存token,taken为钥匙
      layer.msg("来了,老弟", () => {
        location.href = "/index.html";
        localStorage.setItem("token", obj.token);
      });
    });
  });
});
